<template>
	<view :class="'flex flex-row flex-center relative ' + extraClass">
		<view class='w-10 h-10 border b-color-2 relative flex flex-center rounded-n' v-for="i in data" 
			:class="{'mr-4-4': i !== data.length - 1,'bg-disable-op20' : disabled}" :key="i">
			<view class='twinkling absolute inset-y-2-3 x-center w-min bg-black' :class="{'hidden': i !== current || !isFocus || disabled}"></view>
			<text :style="{'font-size': fontSize + 'px'}" :class="{'color-disable': disabled}">{{inputModel[i]}}</text>
		</view>
		<input class='input absolute top-0 h-full z-10 right-0' @input="input" :value="hideVal" :maxlength="digit" type="number"
			@focus="focus" :focus="autoFocus" @blur="blur" :disabled="disabled"/>
	</view>
</template>

<script>
	import { ref,reactive,onMounted,getCurrentInstance } from "vue";
	export default {
		name:"CaptchaInput",
		props: {
			digit: {
				default: 4,
				type: Number
			},
			autoFocus: Boolean,
			extraClass: {
				default: '',
				type: String
			},
			disabled: Boolean
		},
		setup(props,ctx){
			const current = ref(0);
			const hideVal = ref("");
			//字体大小 需计算 与光标一致高度
			const fontSize = ref(30);
			const isFocus = ref(false);
			let inputModel = {};
			let data = [];
			for(let i=0;i<props.digit;i++){
				inputModel[i] = '';
				data.push(i);
			}
			inputModel = reactive(inputModel);
			data = ref(data);
			let lastDigit = null;
			function input(e){
				const val = e.detail.value;
				const len = val.length;
				current.value = len;
				for(let i=0;i<data.value.length;i++){
					const ch = val.charAt(i);
					inputModel[i] = ch === undefined ? '' : ch;
				}
				if(len === props.digit && lastDigit < len){
					ctx.emit("finish",val);
				}
				lastDigit = len;
			}
			function focus(){
				// console.log("doFocus");
				isFocus.value = true;
			}
			function blur(){
				// console.log("blur");
				isFocus.value = false;
			}
			onMounted(() => {
				//计算光标高度
				const { ctx } = getCurrentInstance();
				const query = uni.createSelectorQuery().in(ctx);
				let view = query.select(".twinkling");
				view.boundingClientRect(data => {
					fontSize.value = data.height;
				}).exec();
			});
			return {
				data,
				input,
				hideVal,
				current,
				fontSize,
				inputModel,
				focus,
				blur,
				isFocus
			};
		}
	}
</script>

<style>
	.input{
		left:-999px
	}
	@keyframes twinkling {
		0% {
			opacity: 1;
		}
		
		49% {
			opacity: 1;
		}
		
		50% {
			opacity: 0;
		}
		
		99% {
			opacity: 0;
		}
		100% {
			opacity: 1;
		}
	}
	.twinkling{
		animation: twinkling 1s infinite ease;
	}
</style>
